package com.music.controller;

import com.music.util.QiniuCloudUtil;
import com.sun.deploy.net.HttpRequest;
import com.sun.xml.internal.messaging.saaj.util.ByteOutputStream;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.net.URLEncoder;

@Controller
public class FileDownloadController {
   
    @RequestMapping("/downloadFileFromQiniu")
    public void downloadFileFromQiniu(@RequestParam String fileName,HttpServletResponse response) throws IOException {
        // 字节输入流
        InputStream inputStream = null;
        // 字节输出流
        OutputStream os = null;
        try {
            // 通过七牛云工具类获取下载链接
            String downloadURL = QiniuCloudUtil.getDownloadUrl(fileName);
            // 构建输入流
            inputStream = new URL(downloadURL).openStream();

            // 构建字节数组的输出流
            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = inputStream.read(buffer)) != -1) {
                outStream.write(buffer, 0, len);
            }
            inputStream.close();

            byte[] data = outStream.toByteArray();
            response.reset();
            // 设置响应头,Content-Disposition 响应头指示回复的内容该以何种形式展示，是以内联的形式（即网页或者页面的一部分），还是以附件的形式下载并保存到本地
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            response.setContentType("application/octet-stream");
            os = response.getOutputStream();

            os.write(data);
            os.flush();
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                inputStream.close();
            }
            if (os != null) {
                os.close();
            }
        }

    }
}
